﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NetFrame.Auto
{
    public class MessageEncoding
    {
        /// <summary>消息体序列化 </summary>
        public static byte[] Encode(object value)
        {
            SocketModel model=value as SocketModel;
            ByteArray ba=new ByteArray();
            //写入顺序和读取顺序必须保持一致，不一致的话就会读取出错
            ba.WriteByte(model.Type);
            ba.WriteInt(model.Area);
            ba.WriteInt(model.Command);
            if (model.Message != null)//判断消息体是否为null
            {
                ba.WriteByteArray(SerializeUtil.ObjectToByteArray(model.Message));
            }
            byte[] result = ba.GetBuff();
            ba.Close();
            return result;
        }

        /// <summary> 消息体反序列化 </summary>
        public static object Decode(byte[] value)
        {  
            ByteArray ba=new ByteArray(value);
            SocketModel model=new SocketModel();
            //写入顺序和读取顺序必须保持一致，不一致的话就会读取出错
            byte type = ba.ReadByte();
            int area = ba.ReadInt();
            int command = ba.ReadInt();
            //读取类型、区域码、和命令
            model.Type = type;
            model.Area = area;
            model.Command = command;
            if (ba.Readnable)//如果当前内存流中还有数据，说明是有消息体，则读取消息体
            {
                byte[] message = ba.ReadByteArray(ba.Length - ba.Position);
                model.Message = SerializeUtil.ByteArrayToObject(message);
            }
            ba.Close();
            return model;
        }
    }
}
